package com.dragon.www.haier.model.xml;

import android.content.Context;


import com.dragon.www.haier.R;
import com.dragon.www.haier.net.ResourceUtil;

import java.util.List;

/**
 * 指令编码模板工厂
 * 指令格式的创建、修改，字典库的维护
 * Created by Administrator on 2015/11/20 11:39.
 * Author: songxy
 * Email: thinkdata@163.com
 */
public class CodeTemplateFactory {

	private Context context;

	private static final String CODE_TAG = "code";

	private static final String PACKET_TAG = "requestPacket";

	private static CodeTemplateFactory instance;

	private CodeTemplateFactory() {}

	private CodeTemplate template = new CodeTemplate();

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public static CodeTemplateFactory newInstance(Context context) {
		synchronized (CodeTemplateFactory.class) {
			if (instance == null) {
				instance = new CodeTemplateFactory();
			}
		}
		instance.setContext(context);
		loadDictionary();
		return instance;
	}

	public static void loadDictionary() {
		try {
			List<Dictionary> dictionaries = ResourceUtil.getDictionary(
					instance.context, R.raw.dictionary);
			for (Dictionary dictionary : dictionaries) {
					for (DictionaryGroupItem groupItem : dictionary.groupItems) {
						if (dictionary.getType().equals(CODE_TAG)) {
							instance.template.setCodeTemplate(groupItem, groupItem.items);
						}else if (dictionary.getType().equals(PACKET_TAG)) {
							instance.template.setPacketTemplate(groupItem.getGroupName(), groupItem.items);
						}
					}
			}
		}catch (Exception e) {
			throw new CodeException(e.getMessage(), e);
		}
	}

	public CodeTemplate newCodeTemplate() {
		if (this.template.codeTemplate == null || this.template.codeTemplate.size() == 0)
			throw new CodeException("No codeTemplate in dictionary.xml");
		return template;
	}
}
